package com.xiaobingby.admin.config;

import com.xiaobingby.common.util.R;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 未授权返回配置
 *
 * @author XiaoBingBy
 * @date 2018-12-23 20:21
 * @since 1.0
 */
@Component
public class OAuth2AccessDeniedHandlerConfig extends OAuth2AccessDeniedHandler {

    private WebResponseExceptionTranslator exceptionTranslator = new DefaultWebResponseExceptionTranslator();

    private OAuth2ExceptionRenderer exceptionRenderer = new DefaultOAuth2ExceptionRenderer();

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        try {
            ResponseEntity<OAuth2Exception> result = exceptionTranslator.translate(authException);
            ResponseEntity<R<OAuth2Exception>> rResponseEntity = new ResponseEntity<>(R.error(result.getStatusCodeValue(), result.getBody(), result.getBody().getMessage()), result.getHeaders(), result.getStatusCode());
            exceptionRenderer.handleHttpEntityResponse(rResponseEntity, new ServletWebRequest(request, response));
            response.flushBuffer();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
